<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

input {
  padding: 0 0 0 1px;
  width: 70%;
  margin-left: 10px;
}

textarea {
  width: 70%;
  height: 70px;
  margin-left: 10px;
  padding: 1px 0 0 2px;
}
</style>

<template>
  <!-- border: 1px solid blue -->
  <div style=" padding: 10px;height: 75vh;width: 100%;box-sizing: border-box">
    <!-- 功能区域 -->
    <div style="margin: 0 0 10px 0">
      <el-input @keyup="Load" v-model="data.SearchKeyWord" maxlength="30" placeholder="请输入关键字（所有字段可查）"
                style="width: 20%;"
                clearable></el-input>
      <!--      <el-button @click="Load" type="primary" style="margin-left: 10px;">查询</el-button>-->
      <!--打开弹窗的同时，清空文本信息-->
      <el-button style="margin-left: 10px" type="primary" @click="add">新增用户</el-button>
    </div>

    <!--  表格  -->
    <!-- header-cell-style设置头部居中；cell-style设置单元格内容居中;stripe斑马纹 -->
    <!--  sortable实现排序按钮  -->
    <el-table
        :data="data.tableData"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        border
        stripe
        style="width: 98%; border-radius: 5px;margin-left: 1%;box-sizing: border-box"
    >
      <!--      <el-table-column sortable prop="userId" width="80" label="ID"/>-->
      <el-table-column sortable prop="username" width="180" min-width="150" label="用户名"/>
      <el-table-column sortable prop="fullName" width="180" label="姓名"/>
      <el-table-column sortable prop="nickname" width="180" label="昵称"/>
      <el-table-column sortable prop="email" min-width="270" label="电子邮件"/>
      <el-table-column label="头像" min-width="150px">
        <template #default="scope">
          <el-image
              style="width: 50px;height: 50px;object-fit: cover; border-radius: 5px;cursor: pointer;"
              v-if="scope.row.avatar"
              :src="scope.row.avatar"
              alt="头像"
              @click="viewImage(scope.row.avatar)"
          />
          <el-text v-else>未设置头像</el-text>
        </template>
      </el-table-column>
      <el-table-column sortable prop="isDeleted" width="180" label="状态" min-width="100">
        <template #default="scope">
          <span :style="scope.row.isDeleted !== 0 ? { color: 'red', 'font-weight': 'bold' } : {}">
            {{ scope.row.isDeleted === 0 ? '用户活跃中' : '用户已禁用' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column sortable prop="lastLoginTime" min-width="250" label="最后登录时间"/>
      <el-table-column sortable fixed="right" label="操作" min-width="230">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)" :icon="Edit">编辑</el-button>
          <!--@confirm="handleDelete(scope.row.id)"代表二次确认时删除-->
          <el-popconfirm title="确定删除吗?" @confirm="handleDelete(scope.row.userId)">
            <template #reference>
              <el-button link type="primary" :icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 图片预览对话框 -->
    <el-dialog
        v-model="data.dialogVisible"
        width="30%"
    >
      <img :src="data.previewImageUrl" alt="预览图片" style="width: 100%;">
    </el-dialog>

    <!--  分页  -->
    <el-pagination
        style="margin-top: 1%"
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    ></el-pagination>

    <div style="margin: 10px 0">
      <!--   layout，表示需要显示的内容 prev表示上一页，next为下一页 -->
      <!--   jumper表示跳页元素，total表示总条目数，size用于设置每页显示的页码数量-->

      <!--编辑用户弹框-->
      <div>
        <!--   centerDialogVisible是一个变量，需要在script中定义一下，默认为false     -->
        <el-dialog v-model="data.centerDialogVisible" title="请输入更新的用户信息" width="30%" center>
          <el-form :model="data.form" label-width="60px" ref="userTableFormRef">
            <el-form-item style="margin-left: 50px" label="用户名">
              <el-input v-model="data.form.username" disabled style="width: 80%;" placeholder="请输入用户名"/>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="密 码">
              <el-input v-model="data.editPassword" style="width: 80%;" placeholder="请输入更新的密码"/>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="姓 名">
              <el-input v-model="data.form.fullName" style="width: 80%;" placeholder="请输入姓名"/>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="昵 称">
              <el-input v-model="data.form.nickname" style="width: 80%;" placeholder="请输入昵称"/>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="邮 箱">
              <el-input v-model="data.form.email" style="width: 80%;" placeholder="请输入邮箱"/>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="状 态">
              <div class="mb-2 flex items-center text-sm">
                <el-radio-group v-model="data.form.isDeleted" class="ml-4">
                  <el-radio :label="0">活跃</el-radio>
                  <el-radio :label="1">禁用</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="头 像">
              <el-upload v-model="data.form.avatar"
                         :action=" API_BASE_URL + '/avatar/upload'"
                         :on-success="updateAvatar">
                <el-button style="width: 230px" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-form>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="data.centerDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="save">确认</el-button>
            </span>
          </template>
        </el-dialog>
      </div>

      <!--新增用户弹框-->
      <div>
        <!--   centerDialogVisible是一个变量，需要在script中定义一下，默认为false     -->
        <el-dialog v-model="data.addUserDialogVisible" title="请输入新增用户的相关信息" width="30%" center>
          <el-form :model="data.addUserForm" label-width="60px" ref="userTableFormRef">
            <el-form-item style="margin-left: 50px" label="用户名">
              <el-input v-model="data.addUserForm.username" style="width: 80%;" placeholder="请输入用户名"/>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="密 码">
              <el-input v-model="data.addUserForm.password" style="width: 80%;" placeholder="请输入密码"/>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="昵 称">
              <el-input v-model="data.addUserForm.nickname" style="width: 80%;" placeholder="请输入昵称"/>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="姓 名">
              <el-input v-model="data.addUserForm.fullName" style="width: 80%;" placeholder="请输入姓名"/>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="邮 箱">
              <el-input v-model="data.addUserForm.email" style="width: 80%;" placeholder="请输入邮箱"/>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="状 态">
              <div class="mb-2 flex items-center text-sm">
                <el-radio-group v-model="data.addUserForm.isDeleted" class="ml-4">
                  <el-radio :label="0">活跃</el-radio>
                  <el-radio :label="1">禁用</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="头 像">
              <el-upload v-model="data.addUserForm.avatar"
                         :action=" API_BASE_URL + '/avatar/upload'"
                         :on-error="handleUploadError"
                         :on-success="addUserAvatar">
                <el-button style="width: 230px" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-form>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="data.addUserDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="addUserSave">确认</el-button>
            </span>
          </template>
        </el-dialog>
      </div>

    </div>
  </div>

  <div style="height: 8vh;">

  </div>
</template>

<script setup>
//只需在script标签中添加setup，组件只需引入不用注册，
// 属性和方法也不用返回，也不用写setup函数，也不用写export default ，
// 甚至是自定义指令也可以在我们的template中自动获得
import {API_BASE_URL} from '@/config';
import {reactive, ref} from "vue";
import {Delete, Edit} from '@element-plus/icons-vue'
import request from "../utils/request.js";
//初始化表格
import {ElLoading, ElMessage} from 'element-plus';
import {useRouter} from "vue-router";

const dataString = localStorage.getItem('data');
// 通过JSON.parse转换字符串为对象
const userLoginData = dataString ? JSON.parse(dataString) : null;

const userTableFormRef = ref();

const router = useRouter();

//相当于data(){}
const data = reactive({
  //弹窗默认关闭
  centerDialogVisible: false,
  //弹窗默认关闭
  addUserDialogVisible: false,
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 5,
  //搜索输入框
  SearchKeyWord: "",
  //数据条数
  total: 0,
  //表格数据
  tableData: [],
  //编辑表单
  form: {},
  editPassword: "",
  //新增用户表单
  addUserForm: {
    id: "",
    username: "",
    password: "",
    nickname: "",
    fullName: "",
    email: "",
    avatar: "",
    isDeleted: ""
  },
  editUserId: "",
  dialogVisible: false,
  previewImageUrl: ''
});

const Load = () => {
  let loadingInstance = ElLoading.service({fullscreen: true}); // 启动全屏加载动画
  request.get(`/user/getAll?current=${data.currentPage}&size=${data.pageSize}&SearchKeyWord=${data.SearchKeyWord}`)
      .then((response) => {
        data.tableData = response.data.records;
        data.total = response.data.total;
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
      .finally(() => {
        loadingInstance.close(); // 无论请求成功或失败，都关闭加载动画
      });
};

Load()

//改变分页大小
const handleSizeChange = (pageSize) => {
  data.currentPage = 1
  data.pageSize = pageSize
  Load()
}

//去到第几页
const handleCurrentChange = (currentPage) => {
  data.currentPage = currentPage
  Load()
}

//删除用户
const handleDelete = (id) => {
  request.delete("/user/deleteById/" + id).then((response) => {
    if (response.code === 200) {
      ElMessage.info(response.data)
    } else {
      ElMessage.error(response.data)
    }
  });
  handleCurrentChange(1);
};


//添加用户
const add = () => {
  data.addUserDialogVisible = true;
};


const addUserAvatar = (res) => {
  data.addUserForm.avatar = res.data
}

//编辑用户信息
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));//让form对象独立出来，还能包含那一行的数据
  data.centerDialogVisible = true;
  data.editUserId = row.userId;
};

const updateAvatar = (res) => {
  data.form.avatar = res.data
}


//表单点击确认执行：关闭表单；向后端传数据
const save = async () => {
  data.centerDialogVisible = false;
  data.form.password = data.editPassword;
  try {
    const response = await request.put("/user/edit", data.form);
    if (response.code === 200) {
      ElMessage.info(response.data)
    } else {
      ElMessage.error(response.data)
    }
  } catch (error) {
    ElMessage.error("更新失败")
  }
  Load();
  if (data.form.userId === userLoginData.userId) {
    window.location.reload();//页面刷新  刷新header页面数据
  }
  // 更新本地存储的用户头像和昵称
  if (userLoginData.userId === data.editUserId) {
    userLoginData.avatar = data.form.avatar;
    userLoginData.nickname = data.form.nickname;
    localStorage.removeItem("data");
    localStorage.setItem("data", JSON.stringify(userLoginData));
  }
};

const addUserSave = () => {
  data.addUserDialogVisible = false;
  console.log("添加用户功能——前端传递的数据:", data.addUserForm)
  request.post("/user/push", data.addUserForm).then((response) => {
    if (response.code === 200) {
      ElMessage.info(response.data)
    } else {
      ElMessage.error(response.data)
    }
    Load();
  }).catch((error) => {
    console.error("添加用户失败：", error);
  });
}

// 添加到 <script> 标签中
const handleUploadError = (err, file, fileList) => {
  // 这里你可以自定义错误提示
  // err 是一个错误对象，包含了错误信息
  // file 是出现错误的那个文件对象
  // fileList 是当前的上传文件列表
  ElMessage.error('上传失败');
};

// 点击图片时触发的功能，用于打开对话框并展示图片
const viewImage = (url) => {
  data.previewImageUrl = url;
  data.dialogVisible = true;
};
</script>
